# -*- coding: utf-8 -*-
#! /usr/bin/env python

from PySide.QtCore import Qt


_ADD, _DELETE, _INSERT = range(3) 
_ROOT, _DEPTH, _WIDTH = range(3)


def int_to_checkstate(i):
    i = int(i)
    return {
            0 : Qt.CheckState.Unchecked,
            1 : Qt.CheckState.PartiallyChecked,
            2 : Qt.CheckState.Checked,
        }.get(i, Qt.CheckState.Unchecked)

def checkstate_to_int(c):
    return {
            Qt.CheckState.Unchecked: 0,
            Qt.CheckState.PartiallyChecked: 1,
            Qt.CheckState.Checked: 2,
        }.get(c, 0)

def unescape(s):
    s = s.replace("&lt;", "<")
    s = s.replace("&gt;", ">")
    s = s.replace("&quot;", "\"")
    # this has to be last:
    s = s.replace("&amp;", "&")
    return s
   
def create_dirs(dir):
    if not os.path.exists(dir): os.mkdir(dir)
    if not os.path.exists(dir + "/cur"): os.mkdir(dir + "/cur")
    if not os.path.exists(dir + "/new"): os.mkdir(dir + "/new")
    if not os.path.exists(dir + "/tmp"): os.mkdir(dir + "/tmp")
    # Create Maildir++ folder marker
    file(dir + "/maildirfolder", "w").close()

class Node(object):
    def __init__(self, id = 0, title = '', checked = False, expanded = True, parent = None):
        self.id = id
        self.parent = parent
        self.title = title
        self.checked = checked
        self.expanded = expanded

            
class Tree(object):
    def __init__(self):
        self.nodes = []

    def get_index(self, id):
        for index, node in enumerate(self.nodes):
            if node.identifier == id:
                break
        return index

    def create_node(self, id, title = '', checked = False, parent = None):
        node = Node(id, title)
        self.nodes.append(node)
        return node

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes
                if node.identifier is identifier]

                
if __name__ == "__main__":
    tree = Tree()
    tree.create_node(1, "harry")  # root node
    tree.create_node(3, "jane", parent = 1)
    tree.create_node(4, "bill", parent = 1)
    tree.create_node(5, "joe", parent = 3)
    tree.create_node(6, "diane", parent = 3)
    tree.create_node(7, "george", parent = 6)
    tree.create_node(8, "mary", parent = 6)
    tree.create_node(9, "jill", parent = 7)
    tree.create_node(10, "carol", parent = 8)
    tree.create_node(11, "grace", parent = 9)
    tree.create_node(12, "mark", parent = 3)

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode = _WIDTH):
        print(node)
    print("="*80)                
    
    